<template>
  <div class="code-completion-container">
    <div class="page-header">
      <el-button @click="goBack" icon="ArrowLeft" text>返回</el-button>
      <h1 class="page-title">{{ problem.title }}</h1>
    </div>

    <div class="problem-description">
      <h3>题目描述</h3>
      <p>{{ problem.description }}</p>
      
      <!-- 输入格式 -->
      <div v-if="problem.input_format" class="format-section">
        <h4>输入格式：</h4>
        <pre class="format-content">{{ problem.input_format }}</pre>
      </div>
      
      <!-- 输出格式 -->
      <div v-if="problem.output_format" class="format-section">
        <h4>输出格式：</h4>
        <pre class="format-content">{{ problem.output_format }}</pre>
      </div>
      
      <!-- 输入样例 -->
      <div v-if="testCases && testCases.length > 0" class="sample-section">
        <h4>输入样例：</h4>
        <pre class="sample-content">{{ testCases[0].input }}</pre>
      </div>
      
      <!-- 输出样例 -->
      <div v-if="testCases && testCases.length > 0" class="sample-section">
        <h4>输出样例：</h4>
        <pre class="sample-content">{{ testCases[0].output }}</pre>
      </div>
    </div>

    <div class="editor-section">
      <div class="editor-header">
        <h3>代码补全</h3>
        <div class="editor-actions">
          <el-select v-model="selectedLanguage" placeholder="选择语言" size="small">
            <el-option label="Python" value="python" />
            <el-option label="JavaScript" value="javascript" />
            <el-option label="Java" value="java" />
            <el-option label="C++" value="cpp" />
          </el-select>
          <el-button type="primary" @click="runCode" :loading="running">运行</el-button>
          <el-button @click="submitCode" :loading="submitting">提交</el-button>
        </div>
      </div>

      <div class="code-view" @mousedown.prevent>
        <!-- 调试信息 -->
        <div v-if="renderedLines.length === 0" class="debug-info" style="color: #ff6b6b; padding: 10px;">
          调试信息: 没有解析到代码行，请检查题目数据
        </div>
        
        <div class="code-line" v-for="(line, lineIdx) in renderedLines" :key="lineIdx">
          <span class="line-number">{{ lineIdx + 1 }}</span>
          <span class="code-chunks">
            <template v-for="(chunk, chunkIdx) in line" :key="chunkIdx">
              <span v-if="chunk.type === 'text'" class="code-text">{{ chunk.value }}</span>
              <input
                v-else
                class="blank-input"
                v-model="answers[chunk.id]"
                :placeholder="chunk.placeholder || '在此填写'"
                :maxlength="chunk.maxLength || 100"
                @keydown.stop
                @mousedown.stop
                @focus="onInputFocus"
                @blur="onInputBlur"
              />
            </template>
          </span>
        </div>
      </div>
    </div>

    <div class="output-section">
      <h3>运行结果</h3>
      <pre class="output-box">{{ output }}</pre>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { problemsApi } from '@/api/problems';
import { runCode as runCodeApi, submitCode as submitCodeApi } from '@/api/judge';
import type { Problem, JudgeResult } from '@/types';

interface BlankSpec {
  id: string; // 唯一ID，例如 BLANK1
  placeholder?: string;
  maxLength?: number;
}

const router = useRouter();
const route = useRoute();

const selectedLanguage = ref<'python' | 'javascript' | 'java' | 'cpp'>('python');
const running = ref(false);
const submitting = ref(false);
const output = ref('');
const problem = ref<Problem>({} as Problem);
const testCases = ref<any[]>([]);

// 答案存储
const answers = ref<Record<string, string>>({});

// 将模板拆分为渲染行，非空白为只读文本，___渲染为可编辑输入
const renderedLines = computed(() => {
  console.log('renderedLines computed - problem.value:', problem.value);
  console.log('renderedLines computed - problem.value.answer:', problem.value.answer);
  
  if (!problem.value.answer) {
    console.log('没有答案模板，返回空数组');
    return [];
  }
  
  const lines = (problem.value.answer as string).split('\n');
  console.log('解析代码模板:', lines);
  const result: Array<Array<{ type: 'text' | 'blank'; value?: string; id?: string; placeholder?: string; maxLength?: number }>> = [];
  const blankPattern = /___/g;

  for (const line of lines) {
    const chunks: Array<{ type: 'text' | 'blank'; value?: string; id?: string; placeholder?: string; maxLength?: number }> = [];
    let lastIndex = 0;
    let match: RegExpExecArray | null;
    let blankCount = 0;

    while ((match = blankPattern.exec(line)) !== null) {
      if (match.index > lastIndex) {
        chunks.push({ type: 'text', value: line.slice(lastIndex, match.index) });
      }
      const id = `BLANK${blankCount + 1}`;
      chunks.push({ 
        type: 'blank', 
        id, 
        placeholder: '在此填写代码', 
        maxLength: 100 
      });
      blankCount++;
      lastIndex = match.index + match[0].length;
    }

    if (lastIndex < line.length) {
      chunks.push({ type: 'text', value: line.slice(lastIndex) });
    }

    result.push(chunks);
  }
  console.log('解析结果:', result);
  return result;
});

// 获取问题详情
const loadProblem = async () => {
  try {
    const problemId = parseInt(route.params.id as string);
    console.log('加载问题ID:', problemId);
    const response = await problemsApi.getProblem(problemId);
    console.log('获取到的问题数据:', response);
    problem.value = response;
    
    // 检查问题类型
    if (problem.value.type !== 'code' && problem.value.type !== 'code_completion') {
      ElMessage.error('此页面仅适用于编程题目');
      router.push('/problems');
      return;
    }
    
    console.log('问题类型:', problem.value.type);
    console.log('问题答案模板:', problem.value.answer);
    
    // 设置默认语言
    selectedLanguage.value = (problem.value.language as 'python' | 'javascript' | 'java' | 'cpp') || 'python';
    
    // 解析测试用例
    parseTestCases();
    
    // 初始化答案
    initializeAnswers();
  } catch (error) {
    console.error('加载问题失败:', error);
    ElMessage.error('加载问题失败，请检查网络连接');
  }
};

// 解析测试用例
const parseTestCases = () => {
  if (problem.value.test_cases) {
    if (Array.isArray(problem.value.test_cases)) {
      testCases.value = problem.value.test_cases;
    } else if (typeof problem.value.test_cases === 'string') {
      try {
        const parsed = JSON.parse(problem.value.test_cases);
        if (Array.isArray(parsed)) {
          testCases.value = parsed;
        } else if (parsed.test_cases && Array.isArray(parsed.test_cases)) {
          testCases.value = parsed.test_cases;
        }
      } catch (error) {
        console.error('解析测试用例失败:', error);
        testCases.value = [];
      }
    }
  } else {
    testCases.value = [];
  }
};

// 初始化答案
const initializeAnswers = () => {
  answers.value = {};
  // 为每个空白处初始化答案
  renderedLines.value.forEach(line => {
    line.forEach(chunk => {
      if (chunk.type === 'blank' && chunk.id) {
        answers.value[chunk.id] = '';
      }
    });
  });
};

const goBack = () => {
  router.back();
};

const onInputFocus = (event: Event) => {
  const target = event.target as HTMLInputElement;
  target.style.borderColor = '#409eff';
  target.style.boxShadow = '0 0 0 2px rgba(64, 158, 255, 0.2)';
};

const onInputBlur = (event: Event) => {
  const target = event.target as HTMLInputElement;
  target.style.borderColor = '#2c3654';
  target.style.boxShadow = 'none';
};

const buildUserCode = () => {
  // 将答案替换回模板
  let code = (problem.value.answer as string) || '';
  
  // 按照顺序替换每个___
  const blankKeys = Object.keys(answers.value).sort();
  for (const key of blankKeys) {
    const value = answers.value[key];
    const filledValue = value.trim() || '___';
    // 替换第一个___为答案
    const index = code.indexOf('___');
    if (index !== -1) {
      code = code.substring(0, index) + filledValue + code.substring(index + 3);
    }
  }
  return code;
};

const runCode = async () => {
  const code = buildUserCode();
  if (!code || code.includes('___')) {
    ElMessage.warning('请先填写所有空白处');
    return;
  }
  
  running.value = true;
  try {
    const response = await runCodeApi({
      problem_id: problem.value.id,
      code: code,
      language: selectedLanguage.value
    });
    
    if (response.error_message) {
      output.value = `错误信息:\n${response.error_message}`;
    } else if (response.test_cases && response.test_cases.length > 0) {
      output.value = response.test_cases.map((testCase, index) => 
        `测试用例 ${index + 1}:\n输入: ${testCase.input}\n期望输出: ${testCase.expected_output}\n实际输出: ${testCase.actual_output || 'N/A'}\n状态: ${testCase.status}\n`
      ).join('\n');
    } else {
      output.value = '运行成功，但无输出结果';
    }
  } catch (error) {
    console.error('运行代码失败:', error);
    output.value = '运行失败，请检查代码语法';
  } finally {
    running.value = false;
  }
};

const submitCode = async () => {
  const code = buildUserCode();
  if (!code || code.includes('___')) {
    ElMessage.warning('请先填写所有空白处');
    return;
  }
  
  submitting.value = true;
  try {
    const response = await submitCodeApi({
      problem_id: problem.value.id,
      code: code,
      language: selectedLanguage.value
    });
    
    if (response.status === 'AC') {
      ElMessage.success('提交成功！答案正确');
    } else {
      ElMessage.warning(`提交完成，状态: ${response.status}`);
    }
    
    // 显示详细结果
    if (response.test_cases && response.test_cases.length > 0) {
      output.value = response.test_cases.map((testCase, index) => 
        `测试用例 ${index + 1}:\n输入: ${testCase.input}\n期望输出: ${testCase.expected_output}\n实际输出: ${testCase.actual_output || 'N/A'}\n状态: ${testCase.status}\n`
      ).join('\n');
    }
  } catch (error) {
    console.error('提交代码失败:', error);
    ElMessage.error('提交失败，请重试');
  } finally {
    submitting.value = false;
  }
};

// 获取结果状态文本
const getResultStatusText = (status: string) => {
  switch (status) {
    case 'AC': return '通过';
    case 'WA': return '答案错误';
    case 'CE': return '编译错误';
    case 'TLE': return '超时';
    case 'MLE': return '内存超限';
    case 'RE': return '运行时错误';
    case 'PE': return '格式错误';
    default: return status || '未知';
  }
};

onMounted(() => {
  loadProblem();
});
</script>

<style scoped lang="scss">
.code-completion-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.page-title { 
  font-size: 22px; 
  font-weight: 600; 
  margin: 0;
}

.problem-description {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.problem-description h3 {
  margin-top: 0;
  margin-bottom: 12px;
  color: #333;
}

.problem-description p {
  margin-bottom: 16px;
  line-height: 1.6;
  color: #666;
}

.format-section,
.sample-section {
  margin: 16px 0;
}

.format-section h4,
.sample-section h4 {
  color: #409eff;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 600;
}

.format-content,
.sample-content {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 12px;
  margin: 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-word;
  color: #495057;
  overflow-x: auto;
}

.editor-section {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.editor-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.editor-header h3 {
  margin: 0;
  color: #333;
}

.editor-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.code-view {
  background: #0b1020;
  color: #e6f1ff;
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
  border-radius: 8px;
  padding: 12px;
  overflow: auto;
  border: 1px solid #2c3654;
}

.code-line {
  display: flex;
  align-items: flex-start;
  min-height: 20px;
}

.line-number {
  display: inline-block;
  width: 32px;
  color: #6b7480;
  user-select: none;
  text-align: right;
  padding-right: 8px;
  font-size: 12px;
}

.code-chunks {
  flex: 1;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.code-text { 
  white-space: pre; 
  color: #e6f1ff;
}

.blank-input {
  background: #1a2138;
  border: 1px solid #2c3654;
  color: #fff;
  min-width: 80px;
  max-width: 60%;
  padding: 2px 6px;
  border-radius: 4px;
  margin: 0 4px;
  font-family: inherit;
  font-size: inherit;
}

.blank-input:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.output-section { 
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.output-section h3 {
  margin-top: 0;
  margin-bottom: 12px;
  color: #333;
}

.output-box {
  background: #0b1020;
  color: #e6f1ff;
  border-radius: 8px;
  padding: 12px;
  min-height: 100px;
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
  font-size: 13px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-word;
  overflow-x: auto;
  border: 1px solid #2c3654;
}

@media (max-width: 768px) {
  .code-completion-container {
    padding: 16px;
  }
  
  .editor-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .editor-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>
